/**
 * 
 */
package com.study.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author Administrator
 * @date 2019年6月15日
 */
public class EchoClient2 {
    private Selector selector;
    
    private ByteBuffer sendBuf = ByteBuffer.allocate(20);
    
    private ByteBuffer revBuf = ByteBuffer.allocate(20);
    
    public EchoClient2(){
        try {
            System.out.println("正在连接服务器...");
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
            socketChannel.connect(new InetSocketAddress("localhost",8777));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
 
    public void service() throws IOException {
    	try {
    		while (selector.isOpen() && selector.select() > 0){
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (key.isConnectable()){
                        connect(key);
                    }
                    
                    if(key.isReadable() || key.isWritable()){
                    	
                    	process(key);
                    }
                    

                    //keys.clear();
                }
            }
		} catch (Exception e) {
			e.printStackTrace();
		}         
    }
 
    private void connect(SelectionKey key) {
        try {
            SocketChannel sc = (SocketChannel) key.channel();
            if (sc.isConnectionPending()){
                sc.finishConnect();
                System.out.println("服务器连接成功");
                sc.register(selector,SelectionKey.OP_READ
                        | SelectionKey.OP_WRITE);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务器连接失败");
        }
    }
//    private void read(SelectionKey key) {
//        try {
//            revBuf.clear();
//            SocketChannel sc = (SocketChannel) key.channel();
//            int read = sc.read(revBuf);
//            if (read>0) {
//                revBuf.flip();
//                String recText = new String(revBuf.array(), 0, read);
//                System.out.println(recText);
//                if (recText.equals("quit")) {
//                    key.channel().close();
//                    key.cancel();
//                    return;
//                }
//                sc.register(selector, SelectionKey.OP_WRITE);
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
    private void process(SelectionKey key) {
        try {
        	SocketChannel sc = (SocketChannel) key.channel();
            revBuf.clear();
            int read = sc.read(revBuf);
            if (read>0) {
                revBuf.flip();
                String recText = new String(revBuf.array(), 0, read);
                System.out.println(recText);
                if (recText.equals("byebye")) {
                    key.channel().close();
                    key.cancel();
                    return;
                }
                //sc.register(selector, SelectionKey.OP_WRITE);
            }
            
            sendBuf.clear();
            //Thread.sleep(500);
            Scanner scanner = new Scanner(System.in);  
            //这里有问题： 每次的应答都会延迟一次
            /*
123
1
[ECHO] 123
3
[ECHO] 1
..
原因可能是客户端在等待输入的时候，服务器端的数据还没有回来， 待验证。
             */
            String message = scanner.nextLine();  //阻塞
            sendBuf.put(message.getBytes());
            sendBuf.flip();
            sc.write(sendBuf);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) throws IOException {
        new EchoClient2().service();
    }
}